package org.jpro.config;

import javax.servlet.Servlet;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;

/**
 * <P>功能描述 : druid提供的web页面的监控后台 </P>
 * <P>File name : DruidConfig </P>
 * <P>Author : 王泽浩 </P>
 * <P>E-Mail : 1028625100@qq.com </P>
 * <P>Date : 2017/2/25 上午12:20</P>
 */
@Slf4j
@Setter
@Getter
@ToString
@Configuration
@ConfigurationProperties(prefix = "spring.datasource.druid")
public class DruidConfig {

    /**
     * 可以登陆的IP
     */
    private String allow = "127.0.0.1";

    /**
     * 登陆的用户账号
     */
    private String name = "admin";

    /**
     * 密码
     */
    private String password = "admin";

    /**
     * 映射地址
     */
    private String requestMapping = "/druid/*";

    /**
     * 过滤规则
     */
    private String[] urlPatterns = { "/*" };

    /**
     * 不需要忽略的格式信息
     */
    private String exclusions = "/static/*,*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*";

    /**
     * 是否能够重置数据
     */
    private Boolean resetEnable = true;

    @Bean(name = "druidServlet")
    public Servlet druidServlet() {
        return new StatViewServlet();
    }

    /**
     * 注册一个StatViewServlet
     * @return
     */
    @Bean
    @DependsOn("druidServlet")
    public ServletRegistrationBean druidServletRegistrationBean(@Qualifier("druidServlet") Servlet druidServlet) {

        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(druidServlet, this.requestMapping);
        // 添加初始化参数：initParams
        // 白名单：
        servletRegistrationBean.addInitParameter("allow", this.allow);
        // 登录查看信息的账号密码.
        servletRegistrationBean.addInitParameter("loginUsername", this.name);
        servletRegistrationBean.addInitParameter("loginPassword", this.password);
        // 是否能够重置数据.
        servletRegistrationBean.addInitParameter("resetEnable", this.resetEnable.toString());
        return servletRegistrationBean;
    }

    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
        // 添加过滤规则.
        filterRegistrationBean.addUrlPatterns(this.urlPatterns);
        // 添加不需要忽略的格式信息.
        filterRegistrationBean.addInitParameter("exclusions", this.exclusions);
        return filterRegistrationBean;
    }

}
